<?php
namespace app\store\model;

use think\Db;

class Device extends Base
{
    /**
     * 列表
     */
    public function index()
    {
        $total = $this->dbConn($this->dbShDevice)
            ->where(['del' => 0])
            ->count();
        $res = $this->dbConn($this->dbShDevice)
            ->where(['del' => 0])
            ->order('id', 'desc')
            ->select()->toArray();
        if (!count($res)) {
            return $this->toback(0, '', [], 0);
        }
        $arys = [];
        foreach ($res as $v) {
            //商家
            $storeOne = $this->dbConn($this->dbStoreUser)
                ->where('store_user_id', $v['store_id'])
                ->find();
            $shop_name = $storeOne ? $storeOne['user_name'] : '-';
            //左门
            $door01 = $this->dbConn($this->dbShdDoor)
                ->where('device_id', $v['id'])
                ->where('door_type', 1)
                ->find();
            $door01status = $door01['status']==1 ? '关门' : '开门';
            $door01bind = $door01['is_bind']==1 ? '未绑定' : '已绑定';
            $door01name = '左门【'.$door01['title'].'】';
            $door01name .= '<br>编号【'.$door01['door_no'].'】';
            $door01name .= '<br>星云开物【'.$door01bind.'】';
            if ($door01['is_bind'] == 1) {
                $door01name .= '<a href="'.url('store/shouhuo.device/bind?id='.$door01['id']).'">绑定</a>';
            } else {
                $door01name .= '<a href="'.url('store/shouhuo.device/unbind?id='.$door01['id']).'&type=1">解绑</a>';
            }
            $door01name .= '<br>状态【'.$door01status.'】';
            if ($door01['status'] == 1) {
                $door01name .= '<a href="'.url('store/shouhuo.device/dooropen?id='.$door01['id']).'">开门</a>';
            }
            //右门
            $door02 = $this->dbConn($this->dbShdDoor)
                ->where('device_id', $v['id'])
                ->where('door_type', 2)
                ->find();
            $door02name = '-';
            if ($door02) {
                $door02status = $door02['status']==1 ? '关门' : '开门';
                $door02bind = $door02['is_bind']==1 ? '未绑定' : '已绑定';
                $door02name = '左门【'.$door02['title'].'】';
                $door02name .= '<br>编号【'.$door02['door_no'].'】';
                $door02name .= '<br>星云开物【'.$door02bind.'】';
                if ($door02['is_bind'] == 1) {
                    $door02name .= '<a href="'.url('store/shouhuo.device/bind?id='.$door02['id']).'">绑定</a>';
                } else {
                    $door02name .= '<a href="'.url('store/shouhuo.device/unbind?id='.$door02['id']).'&type=2">解绑</a>';
                }
                $door02name .= '<br>状态【'.$door02status.'】';
            }
            $arys[] = [
                'id' => $v['id'],
                'imei' => $v['imei'],
                'title' => $v['title'],
                'shop_name' => $shop_name,
                'door01' => $door01name,
                'door02' => $door02name,
                'uptime' => $v['uptime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }
    /**
     * 详情
     */
    public function getOne($id)
    {
        $res = $this->dbConn($this->dbShDevice)
            ->where(['del' => 0, 'id' => $id])
            ->find();
        if (!$res) {
            return $this->toback(-2, '没有记录');
        }
        //商家
        $storeOne = $this->dbConn($this->dbStoreUser)
            ->where('store_user_id', $res['store_id'])
            ->find();
        $shop_name = $storeOne ? $storeOne['user_name'] : '-';
        //左门
        $door01 = $this->dbConn($this->dbShdDoor)
            ->where('store_id', $res['store_id'])
            ->where('device_id', $id)
            ->where('door_type', 1)
            ->find();
        //右门
        $door02 = $this->dbConn($this->dbShdDoor)
            ->where('store_id', $res['store_id'])
            ->where('device_id', $id)
            ->where('door_type', 2)
            ->find();
        $door02_id = $door02 ? $door02['id'] : 0;
        $door02_name = $door02 ? $door02['title'] : '';
        $door02_no = $door02 ? $door02['door_no'] : '';
        $arys = [
            'id' => $res['id'],
            'imei' => $res['imei'],
            'title' => $res['title'],
            'shop_name' => $shop_name,
            'door01_id' => $door01['id'],
            'door01_name' => $door01['title'],
            'door01_no' => $door01['door_no'],
            'door02_id' => $door02_id,
            'door02_name' => $door02_name,
            'door02_no' => $door02_no,
            'uptime' => $res['uptime'],
        ];
        return $this->toback(0, '', $arys);
    }

    /**
     * 新增
     * @param array $pas【shop，title，serial】
     */
    public function add($pas)
    {
        $storeOne = $this->dbConn($this->dbStoreUser)
            ->where(['is_delete' => 0, 'user_name' => $pas['shop_name']])
            ->find();
        if (!$storeOne) {
            return $this->toback(-2, '没有该商家');
        }
        $store_id = $storeOne['store_user_id'];
        $deviceOne = $this->dbConn($this->dbShDevice)
            ->where(['del' => 0, 'imei' => $pas['imei']])
            ->find();
        if ($deviceOne) {
            return $this->toback(-2, '该编号的设备已存在');
        }
        Db::startTrans();
        try {
            //机器
            $lastid = $this->dbConn($this->dbShDevice)->insertGetId([
                'store_id' => $store_id, 'imei' => $pas['imei'], 'title' => $pas['title'],
                'addtime' => $this->toDate(), 'uptime' => $this->toDate(),
            ]);
            if (!$lastid) {
                return $this->toback(-1, 'jiqi false');
            }
            //左门
            $leftid = $this->dbConn($this->dbShdDoor)->insertGetId([
                'store_id' => $store_id, 'device_id' => $lastid,
                'title' => $pas['door01_name'], 'door_type' => 1, 'door_no' => $pas['door01_no'],
                'addtime' => $this->toDate(), 'uptime' => $this->toDate(),
            ]);
            if (!$leftid) {
                return $this->toback(-1, 'left false');
            }
            //右门
            if ($pas['door02_no']) {
                $rightid = $this->dbConn($this->dbShdDoor)->insertGetId([
                    'store_id' => $store_id, 'device_id' => $lastid,
                    'title' => $pas['door02_name'], 'door_type' => 2, 'door_no' => $pas['door02_no'],
                    'addtime' => $this->toDate(), 'uptime' => $this->toDate(),
                ]);
                if (!$rightid) {
                    return $this->toback(-1, 'right false');
                }
            }
            Db::commit();
            return $this->toback();
        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
            return $this->toback(-1, 'error');
        }
    }

    /**
     * 修改
     * @param int $id
     * @param array $pas【shop，title，serial】
     */
    public function modify($id, $pas)
    {
        $res = $this->dbConn($this->dbShDevice)
            ->where(['del' => 0, 'id' => $id])
            ->find();
        if (!$res) {
            return $this->toback(-2, '没有记录');
        }
        Db::startTrans();
        try {
            //机器
            $up = $this->dbConn($this->dbShDevice)->where(['id' => $id])
                ->update([
                    'imei' => $pas['imei'], 'title' => $pas['title'],
                    'uptime' => $this->toDate(),
                ]);
            if (!$up) {
                return $this->toback(-1, 'error');
            }
            //左门
            $up = $this->dbConn($this->dbShdDoor)->where('id', $pas['door01_id'])->update([
                'title' => $pas['door01_name'], 'door_no' => $pas['door01_no'], 'uptime' => $this->toDate(),
            ]);
            if (!$up) {
                return $this->toback(-1, 'left false');
            }
            //右门
            if ($pas['door02_no']) {
                $rightid = $this->dbConn($this->dbShdDoor)->where('id', $pas['door02_id'])->update([
                    'title' => $pas['door02_name'], 'door_no' => $pas['door02_no'], 'uptime' => $this->toDate(),
                ]);
                if (!$rightid) {
                    return $this->toback(-1, 'right false');
                }
            }
            Db::commit();
            return $this->toback();
        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
            return $this->toback(-1, 'error');
        }
    }

    /**
     * 星云开物-同步机器列表
     */
    public function listByXykw($xykws)
    {
        foreach ($xykws as $v) {
            //机器
            $deviceOne = $this->dbConn($this->dbShDevice)
                ->where('del', 0)
                ->where('imei', $v['imei'])
                ->find();
            $device_name = 'JQ'.date('YmdHis', time()).rand(100, 999);
            $sbData = [
                'imei' => $v['imei'],
                'sim_card' => $v['sim_card'],
                'uptime' => toDate(),
            ];
            if ($deviceOne) {
                if (!$deviceOne['title']) $sbData['title'] = $device_name;
                if (!$deviceOne['address']) $sbData['address'] = $v['address'];
                $this->dbConn($this->dbShDevice)->where('id', $deviceOne['id'])->update($sbData);
                $device_id = $deviceOne['id'];
            } else {
                $sbData['title'] = $device_name;
                $sbData['address'] = $v['address'];
                $sbData['addtime'] = toDate();
                $device_id = $this->dbConn($this->dbShDevice)->insertGetId($sbData);
            }
            //门
            $doorOne = $this->dbConn($this->dbShdDoor)
                ->where('del', 0)
                ->where('device_id', $device_id)
                ->where('door_no', $v['equipment_id'])
                ->find();
            $mData = [
                //'store_id' => $deviceOne['store_id'],
                'device_id' => $device_id,
                'door_no' => $v['equipment_id'],
                'door_type' => $v['door']=='right' ? 2 : 1,
                'uptime' => toDate(),
            ];
            if ($doorOne) {
                if (!$doorOne['title']) {
                    $mData['title'] = 'M'.date('YmdHis', time()).rand(100, 999);
                }
                $this->dbConn($this->dbShdDoor)->where('id', $doorOne['id'])->update($mData);
            } else {
                $mData['title'] = 'M'.date('YmdHis', time()).rand(100, 999);
                $mData['addtime'] = toDate();
                $this->dbConn($this->dbShdDoor)->insertGetId($mData);
            }
        }
        return $this->toback();
    }

    /**
     * 机器日志
     */
    public function orderAdd($pas)
    {
        $pas['addtime'] = $this->toDate();
        return $this->dbConn($this->dbShOrder)->insertGetId($pas);
    }

    /**
     * 机器日志
     */
    public function orderModify($id, $pas)
    {
        $pas['uptime'] = $this->toDate();
        return $this->dbConn($this->dbShOrder)->where('id',$id )->update($pas);
    }

    /**
     * 机器日志
     */
    public function orderOne($orderno)
    {
        return $this->dbConn($this->dbShOrder)
            ->where('order_sn',$orderno)
            ->find();
    }

    /**
     * 星云开物-通知接口
     * @param array $pas 星云开物的请求数据
     */
    public function xykwNotice($pas)
    {
        $data = $pas['data'];
        $order_sn = isset($data['order_sn'])&&$data['order_sn'] ? $data['order_sn'] : '';
        $tzData = [
            'notity_type' => $data['notity_type'],
            'xykw_json' => json_encode($pas, JSON_UNESCAPED_UNICODE),
            'addtime' => $this->toDate(),
        ];
        if ($order_sn) {
            $tzData['order_sn'] = $order_sn;
        }
        $tzid = $this->dbConn($this->dbShNotice)->insertGetId($tzData);
        $order_sn = isset($data['order_sn'])&&$data['order_sn'] ? $data['order_sn'] : '';
        $lyy_order_sn = isset($data['lyy_order_sn'])&&$data['lyy_order_sn'] ? $data['lyy_order_sn'] : '';
        $notity_type = isset($data['notity_type'])&&$data['notity_type'] ? $data['notity_type'] : '';
        //更新门状态
//            if ($notity_type == 'opendoor_status' && $orderLog) { //开门状态
//                /** {"api_key":"EP2024241620268","code":"200","data":{"notity_type":"opendoor_status","order_sn":"D2024122710412929702"},"ex_code":"0","message":"SUCCESS","random_str":"3beb89451764437abc1831ccad4593c0","sign":"a3df7abdbe795832bbf7ded005302e17"}
//                 */
//                //开门状态是提前更新了
//            }
        if ($order_sn) {
            //更新日志
            $orderLog = $this->dbConn($this->dbShOrder)
                ->where('order_sn', $order_sn)
                ->find();
            if ($orderLog && $lyy_order_sn) {
                $this->dbConn($this->dbShOrder)
                    ->where('id', $orderLog['id'])
                    ->update(['lyy_order_sn' => $lyy_order_sn]);
            }
            if ($notity_type == 'door_closed') { //关门状态
                /** {"api_key":"EP2024241620268","code":"200","data":{"notity_type":"door_closed"},"ex_code":"0","message":"SUCCESS","random_str":"4ccf8c01e4924e0881c8b76a949f73c3","sign":"85d897a7e509866c395e97487769f82b"}
                 */
                $door_info = $orderLog['door_info'] ? json_decode($orderLog['door_info']) : [];
                $doorno = $door_info ? $door_info['door_no'] : '';
                if ($doorno) {
                    $this->dbConn($this->dbShdDoor)
                        ->where('del', 0)
                        ->where('status', 2)
                        ->where('door_no', $doorno)
                        ->update(['status' => 1, 'closetime' => $this->toDate()]);
                }
            }
            //更新商品订单
            if ($notity_type == 'order_info') { //商品订单
                /** {"api_key":"EP2024241620268","code":"200","data":{"create_time":"2024-12-26 17:42:23","is_algorithm":"1","is_sale":"1","lyy_order_sn":"ypl1872216377176227840","notity_type":"order_info","video_image":",https:\/\/heyun.oss-cn-shenzhen.aliyuncs.com\/vending\/videoCodec\/video\/1872216377056522240-20241226174222-0.mp4"},"ex_code":"0","message":"SUCCESS","random_str":"1a48d57af48b4f9e83703eb7be0b7e11","sign":"65c23ca4363f796eb30f0ef1c7ba5280"}
                 */
                $door_info = $orderLog['door_info'] ? json_decode($orderLog['door_info']) : [];
                $doorno = $door_info ? $door_info['door_no'] : '';
                if ($doorno) {
                    $this->dbConn($this->dbShdDoor)
                        ->where('del', 0)
                        ->where('status', 2)
                        ->where('door_no', $doorno)
                        ->update(['status' => 1, 'closetime' => $this->toDate()]);
                }
            }
        }
        if ($notity_type == 'equipment_status') { //门状态
            /** {"api_key":"EP2024241620268","code":"200","data":{"address":"null null null null","camera_status":"3","door":"1","door_status":"1","equipment_id":"91238248","imei":"861433073996853","is_online":"1","memory_status":"1","notity_type":"equipment_status"},"ex_code":"0","message":"SUCCESS","random_str":"daf5d8dcfd504d5093158411c1c6d2db","sign":"c4d08b2cd6468cff7092aa1e3afa019d"}
             * door_status，1关门，2开门
             */
            $doorno = isset($data['equipment_id'])&&$data['equipment_id'] ? $data['equipment_id'] : '';
            $door_status = isset($data['door_status'])&&$data['door_status'] ? $data['door_status'] : '';
            if ($door_status == 1) {
                $this->dbConn($this->dbShdDoor)
                    ->where('del', 0)
                    ->where('status', 2)
                    ->where('door_no', $doorno)
                    ->update(['status' => 1, 'closetime' => $this->toDate()]);
            }
        }
        return $tzid;
    }

    /**
     * 绑定
     * @param int $id 设备ID
     */
    public function bind($door_id)
    {
        $res = $this->dbConn($this->dbShdDoor)
            ->where('id', $door_id)
            ->find();
        if (!$res) {
            return $this->toback(-2, '不存在');
        }
        $up = $this->dbConn($this->dbShdDoor)
            ->where('id', $door_id)
            ->update(['is_bind' => 2, 'bindtime' => toDate()]);
        if (!$up) {
            return $this->toback(-2, 'fail');
        }
        return $this->toback();
    }

    /**
     * 解绑
     * @param int $id 设备ID
     */
    public function unbind($door_id)
    {
        $res = $this->dbConn($this->dbShdDoor)
            ->where('id', $door_id)
            ->find();
        if (!$res) {
            return $this->toback(-2, '不存在');
        }
        $up = $this->dbConn($this->dbShdDoor)
            ->where('id', $door_id)
            ->update(['is_bind' => 1, 'unbindtime' => toDate()]);
        if (!$up) {
            return $this->toback(-2, 'fail');
        }
        return $this->toback();
    }

    /**
     * 开门
     * @param int $id 设备ID
     */
    public function doorOpen($door_id)
    {
        $res = $this->dbConn($this->dbShdDoor)
            ->where('id', $door_id)
            ->find();
        if (!$res) {
            return $this->toback(-2, '不存在');
        }
        $up = $this->dbConn($this->dbShdDoor)
            ->where('id', $door_id)
            ->update(['status' => 2, 'opentime' => toDate()]);
        if (!$up) {
            return $this->toback(-2, 'fail');
        }
        return $this->toback();
    }
}